<template>
  <div class="replenishment-list-wrap table-gl-w">
    <div class="search-w table-filter-form">
      <FilterTable :filterItem="filterItem" :isReset="true" @search="searchByVal" />
    </div>
    <div class="table-gl-con">
      <TableWrap style="flex: 1" @refresh="getTableList">
        <template #headerLeft>
          <a-space>
            <a-button v-if="$authPass('user.supplier.save')" type="primary" size="medium" @click="openEditSupplierDialog()">添加供应商</a-button>
            <a-button v-if="$authPass('user.supplier.enable')" class="gray-outline" size="medium" @click="changeStateBatch(1, '启用')">启用</a-button>
            <a-button v-if="$authPass('user.supplier.enable')" class="gray-outline" size="medium" @click="changeStateBatch(0, '停用')">停用</a-button>
          </a-space>
        </template>
        <template #tableBody>
          <a-table
            class="table-two-line show-border-table"
            ref="tableRef"
            row-key="id"
            :loading="tableLoading"
            @selection-change="selectColumn"
            :row-selection="rowSelection"
            :data="tableList"
            :scroll="{
              y: '100%',
            }"
            size="mini"
            :pagination="false"
          >
            <template #columns>
              <a-table-column data-index="sort" title="序号" :width="45">
                <template #cell="{ rowIndex }">
                  <p>{{ rowIndex + 1 }}</p>
                </template>
              </a-table-column>
              <a-table-column data-index="shop" title="供应商编号" :width="100">
                <template #cell="{ record }">
                  <p class="highlight">{{ record.supplierCode }}</p>
                </template>
              </a-table-column>
              <a-table-column title="供应商名称" :width="100" data-index="supplierName" />
              <a-table-column data-index="status" title="状态" :width="60">
                <template #cell="{ record }">
                  <a-popconfirm :content="`确定是否${record.status === 0 ? '启用' : '停用'}该供应商`" @ok="changeState(record)" type="warning">
                    <a-switch v-model="record.status" checked-text="开" unchecked-text="关" :disabled="!$authPass('user.supplier.enable')" :checked-value="1" :unchecked-value="0" :beforeChange="handleChangeIntercept" />
                  </a-popconfirm>
                </template>
              </a-table-column>
              <a-table-column title="是否注册" :width="80">
                <template #cell="{ record }">
                  <div v-if="!record.register" style="color: #666">
                    <div>未注册</div>
                    <div> <a-button type="text" @click="inviteSupplier(record)">邀请供应商注册</a-button> </div>
                  </div>
                  <template v-else>
                    <p>已注册</p>
                    <p>{{ record.companyName }}</p>
                  </template>
                </template>
              </a-table-column>
              <a-table-column title="结算方式" :width="80">
                <template #cell="{ record }">
                  <p>{{ record.settleType == 1 ? '现结' : '月结' }}</p>
                </template>
              </a-table-column>
              <a-table-column title="联系人" :width="100">
                <template #cell="{ record }">
                  <p>{{ getDefaultUser(record.contactUsers, 'userName') }}</p>
                  <p>{{ getDefaultUser(record.contactUsers, 'mobile') }}</p>
                </template>
              </a-table-column>
              <a-table-column title="开发员" :width="80" data-index="developUname" />
              <a-table-column title="采购员" :width="80" data-index="developUname">
                <template #cell="{ record }">
                  <p>{{ getUserName(record.purchaseUsers) }}</p>
                </template>
              </a-table-column>
              <a-table-column title="添加时间" :width="120">
                <template #cell="{ record }">
                  <p>{{ $setTime(record.gmtCreate, 'YYYY/MM/DD HH:mm') }}</p>
                </template>
              </a-table-column>
              <a-table-column title="备注" :width="120">
                <template #cell="{ record }">
                  <TextLimit>{{ record.remark }}</TextLimit>
                </template>
              </a-table-column>
              <a-table-column title="操作" :width="90">
                <template #cell="{ record }">
                  <a-space>
                    <a-button type="text" @click="openEditSupplierDialog(record)" v-if="$authPass('user.supplier.edit')">编辑</a-button>
                    <a-popconfirm content="确定是否删除该供应商?" v-if="$authPass('user.supplier.edit')" @ok="deleteItem(record)" type="error">
                      <a-button type="text">删除</a-button>
                    </a-popconfirm>
                  </a-space>
                </template>
              </a-table-column>
            </template>
          </a-table>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :total="total" :default-page-size="searchVal.pageSize" :current="searchVal.pageNum" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>
  <!-- 添加编辑供应商 -->
  <AddAndEditSupplier v-if="showEditDialog" :currentItem="currentItem" :isShow="showEditDialog" @closed="showEditDialog = false" @success="getTableList" />
  <a-modal title="邀请供应商入驻到供应商协同系统" :footer="false" v-model:visible="visible" @cancel="visible = false">
    <div style="margin-bottom: 10px; text-align: center">请将以下链接发给供应商联系人，注册供应商协同系统：</div>
    <div style="text-align: center">
      <a-typography-paragraph copyable @copy="copy" class="highlight">{{ url }}</a-typography-paragraph>
    </div>
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref, onMounted, reactive } from 'vue'
  import FilterTable from '@/components/TableFilter.vue'
  import { FilterTableItem } from '@/types/components'
  import { findSupperPage, updateSupplierStatus, deleteSupplier } from '@/api/purchase'
  import AddAndEditSupplier from './components/addAndEditSupplier.vue'
  import TableWrap from '@/components/TableWrap.vue'
  import { Message, Modal } from '@arco-design/web-vue'
  import useUserStore from '@/store/modules/user'
  onMounted(async () => {
    getTableList()
  })

  let visible = ref(false)

  let userInfo = useUserStore()

  console.log(userInfo.companyName, 'userInfouserInfouserInfo')

  let url = ref()

  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  }) as any

  const filterItem = ref<Array<FilterTableItem>>([
    {
      type: 'input_keyword',
      key: 'supplierName',
      keyItems: [
        { label: '供应商名称', value: 'supplierName' },
        { label: '供应商编号', value: 'supplierCode' },
      ],
      keyWidth: '120',
      value: ref(),
      placeholder: '请输入',
      label: '',
      width: 160,
    },

    {
      key: 'status',
      label: '供应商状态',
      value: ref(),
      type: 'select',
      width: 120,
      optionItems: [
        {
          label: '启用',
          value: 1,
        },
        {
          label: '停用',
          value: 0,
        },
      ],
    },
    {
      key: 'register',
      label: '是否注册在线协同',
      value: ref(),
      type: 'select',
      width: 140,
      optionItems: [
        {
          label: '已注册',
          value: 'true',
        },
        {
          label: '未注册',
          value: 'false',
        },
      ],
    },
    {
      key: 'settleType',
      label: '结算方式',
      value: ref(),
      type: 'select',
      width: 100,
      optionItems: [
        {
          label: '月结',
          value: 2,
        },
        {
          label: '现结',
          value: 1,
        },
      ],
    },
    {
      key: 'contactUname',
      label: '联系人',
      value: ref(),
      type: 'input_search',
      width: 100,
    },
    {
      key: 'purchaseUname',
      label: '采购员',
      value: ref(),
      type: 'input_search',
      width: 100,
    },
    {
      key: 'developUname',
      label: '开发员',
      value: ref(),
      type: 'input_search',
      width: 100,
    },
    {
      type: 'keyword_date_range',
      key: 'gmtCreate',
      keyItems: [{ label: '添加日期', value: 'gmtCreate' }],
      keyWidth: '100',
      value: ref(),
      placeholder: '请输入',
      label: '创建时间',
      width: 240,
      attrs: {
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        timePickerProps: { defaultValue: ['00:00:00', '23:59:59'] },
      },
    },
  ])

  let searchVal = ref({
    pageSize: 20,
    pageNum: 1,
  })

  const total = ref(0)
  const tableLoading = ref(false)
  const tableList = ref<Array<any>>([])
  const selectIds = ref([])
  const tableRef = ref()
  const currentItem = ref<any>({})
  const showEditDialog = ref(false)

  function selectColumn(val: any) {
    selectIds.value = val
  }
  // 分页
  function changePage(val: number) {
    searchVal.value.pageNum = val
    getTableList()
  }
  function sizeChange(val: number) {
    searchVal.value.pageSize = val
    getTableList()
  }

  // 通过条件查询
  function searchByVal(info: any) {
    searchVal.value.pageNum = 1
    let filterData = JSON.parse(JSON.stringify(info)) || {}
    getTableList(filterData)
  }
  // 获取商品列表
  async function getTableList(filterData?: any) {
    let params = {
      pageNum: searchVal.value.pageNum,
      pageSize: searchVal.value.pageSize,
      ...filterData,
    }
    delete params.dataType
    tableLoading.value = true
    const res: any = await findSupperPage(params)
    tableLoading.value = false
    tableList.value = res?.data?.records || []
    total.value = res?.data?.total || 0
  }
  // 打开编辑供应商
  function openEditSupplierDialog(item?: any) {
    currentItem.value = item || {}
    showEditDialog.value = true
  }
  function getUserName(users: Array<any>) {
    let arr = users?.map((user: any) => user.userName)
    return arr?.join(',')
  }
  function getDefaultUser(users: Array<any>, key: string) {
    let defaultUser = users?.find((user: any) => user.isDefault) || {}
    return defaultUser[key]
  }

  // 拦截自动切换
  async function handleChangeIntercept() {
    return false
  }
  // 单个切换状态
  async function changeState(row: any) {
    let status = row.status === 1 ? 0 : 1
    const res: any = await updateSupplierStatus({
      ids: [row.id],
      status: status,
    })
    if (res) {
      getTableList()
    }
  }
  // 删除
  async function deleteItem(row: any) {
    const res: any = await deleteSupplier({ idList: [row.id] })
    if (res) {
      Message.success('删除成功')
      getTableList()
    }
  }
  // 批量更改
  function changeStateBatch(status: number, statusText: string) {
    if (!selectIds.value.length) {
      return Message.error('请选择供应商')
    }
    Modal.confirm({
      title: '提示',
      content: `请再次确认，${statusText}选中的供应商`,
      cancelText: '取消',
      okText: '确认',
      titleAlign: 'start',
      onOk: async () => {
        const res: any = await updateSupplierStatus({
          ids: selectIds.value,
          status: status,
        })
        if (res) {
          Message.success(`${statusText}成功`)
          getTableList()
        }
      },
    })
  }

  const copy = () => {
    Message.success('复制成功')
    visible.value = false
  }

  const inviteSupplier = (item: any) => {
    url.value = `${window.location.origin}/#/supplierLogin?companyName=${userInfo.companyName}&id=${item.id}`
    visible.value = true
  }
</script>
<style lang="less" scoped></style>
